package cn.tedu.coolshark.controller;

import cn.tedu.coolshark.mapper.UserMapper;
import cn.tedu.coolshark.pojo.dto.UserDTO;
import cn.tedu.coolshark.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;

/**
 * @author Justin Parker
 * @author 2024/8/22 22:20
 * @version 1.0
 */
@Slf4j
@Api(tags = "用户控制器")
@RestController
@RequestMapping("/v1/users")
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @ApiOperation(value = "用户登录")
    @PostMapping("/login")
    public int login (@RequestBody UserDTO userDTO,@ApiIgnore HttpSession session){
        String username = userDTO.getUsername();
        String password = userDTO.getPassword();
        UserVO userVO = userMapper.selectByUsername(username);
        if (userVO == null){
            /* 用户名不存在 */
            return 3;
        }
        if (!userVO.getPassword().equalsIgnoreCase(password)){
            /* 密码错误 */
            return 2;
        }
        session.setAttribute("user",userVO);
            return 1;
    }

    @ApiOperation(value = "获取当前登录用户信息")
    @GetMapping("/currentUser")
    public UserVO currentUser(@ApiIgnore HttpSession session){
        return (UserVO) session.getAttribute("user");
    }

    @ApiOperation(value = "用户退出")
    @GetMapping("/logout")
    public String logout(@ApiIgnore HttpSession session){
        session.removeAttribute("user");
        return "退出成功";
    }
}
